﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;


namespace CCPSIP.AB
{
    /// <summary>電話表 PDF 檔案下載</summary>

    public class PhoneDocGet : IHttpHandler
    {
        private string kPhoneDocDir = ChrisKit.RootDir + "CCP\\PhoneDoc\\";//ios.ccp.com.tw


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;


            try
            {
                //【01】取得 POST 參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }
                else if (!SipKit.isCCPUser(userInfo.UserType))
                {
                    throw new Exception("Error_02: Cannot access phone list");//無權限存取電話表
                }


                //【02】查詢參數檢查
                //
                string AreaCode = req.Form["AreaCode"];
                string Version = req.Form["Version"];
                if (!Regex.IsMatch(AreaCode, @"^(19)?[0-9]{2}$"))
                    throw new Exception("Error_03: AreaCode Format Error");
                if (!Regex.IsMatch(Version, @"^2[0-9]{3}\.[01][0-9]\.[0-3][0-9]$"))
                    throw new Exception("Error_04: Version Format Error");

                string docFileName = string.Format("{0}_{1}.pdf", AreaCode, Version.Replace(".", "-"));
                string docFilePath = kPhoneDocDir + docFileName;

                //【03】回傳 PDF 檔案
                //
                if (File.Exists(docFilePath))
                {
                    FileInfo fInfo = new FileInfo(docFilePath);
                    resp.AppendHeader("Content-Length", fInfo.Length.ToString());
                    resp.AppendHeader("Last-Modified", fInfo.LastWriteTime.ToUniversalTime().ToString("r"));
                    resp.AppendHeader("Content-Disposition", ChrisKit.getContentDisposition(docFileName));
                    resp.ContentType = "application/pdf";
                    resp.AppendHeader("Cache-Control", "max-age=3600");
                    resp.WriteFile(docFilePath, true);
                }
                else
                {
                    throw new Exception("Error_05: Document Not Found");
                }
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                string resultStr = ChrisKit.Ex2Xml(ex, false);
                int contentLength = System.Text.Encoding.UTF8.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
            }
            finally
            {
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
